#!/bin/bash

# 联系人管理系统
datafile=userinfo.dat

# 输入
input() {
    read -p "enter name,sex,phone:" name sex phone
}

getdata() {
    local msg=$1 emptyok=$2
    while true
    do
        read -p "$msg"
        if test -z "$REPLY"; then
            if test "$emptyok" = 1; then
                break
            fi
            echo "can not be empty"
            continue
        fi
        echo "$REPLY"
        break
    done
}

# 展示所有或者单个
show() {
    if test -z $name; then
        # cat $datafile | sed 's#:# ##g' | column -t
        sed 's/:/ /g' "$datafile" | column -t
    else
        grep -E "$name:$sex:$phone" "$datafile"
        # grep "$name:$sex:$phone" $datafile | \
            # sed 's#:# ##g' | column -t
    fi
}

# 添加
add() {
    input
    grep "$name:$sex:$phone" $datafile
    if test $? -eq 0; then
        echo "用户已经存在"
    else
        echo "$name:$sex:$phone" | tee -a $datafile
        if test $? -eq 0; then
            echo "用户添加成功!"
        fi
    fi
}


# 修改
change() {
    while true
    do
        input
        if test -n $name; then
            grep "$name:$sex:$phone" $datafile | column -t
            new_name=$(getdata "name: [$name] " 1)
            test -z "$new_name" && new_name=$name
            new_sex=$(getdata "sex: [$sex] " 1)
            test -z "$new_sex" && new_sex=$sex
            new_phone=$(getdata "phone: [$phone] " 1)
            test -z "$new_phone" && new_phone=$phone

            # 删除旧记录
            sed -i '/^'"$name:$sex:$phone"'/d' $datafile
            # 添加修改后的记录
            record="$new_name:$new_sex:$new_phone"
            echo "$record" >> "$datafile"
            test $? && break
        else
            echo "请输入完整的用户信息"
        fi
    done
}

# 删除所有或者单个匹配项
del() {
    if [[ -z $name && -z $sex && -z $phone ]]; then
        cat /dev/null > $datafile
    else
        read -p "确认删除? (y/n)" cfm
        if test $cfm = 'y' -o $cfm = 'Y'; then
            sed -i '/^'"$name:$sex:$phone"'/d' $datafile
            if test $? -eq 0; then
                echo "用户删除成功!"
            fi
        else
            return
        fi
    fi
}



while true
do
    read -p $'请输入:1-add 2-show 3-change 4-delete 5-退出\x0a' opt
    case "$opt" in
        1)
            add
            ;;
        2)
            input
            show
            ;;
        3)
            change
            ;;
        4)
            input
            del
            ;;
        5|exit|q)
            exit 1
            ;;
    esac
done
